package com.shimao.celnet.payment.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.shimao.celnet.payment.common.Menu;
import com.shimao.celnet.payment.common.MenuSub;
import com.shimao.celnet.payment.form.ASysPermissionForm;
import com.shimao.celnet.payment.mapper.ASysPermissionMapper;
import com.shimao.celnet.payment.mapper.ASysRolePermissionMapper;
import com.shimao.celnet.payment.model.ASysPermission;
import com.shimao.celnet.payment.service.ASysPermissionService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ensure on 2017/11/12.
 */
@Service
public class ASysPermissionServiceImpl extends BaseServiceImpl<ASysPermission> implements ASysPermissionService {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired(required = false)
    private ASysPermissionMapper aSysPermissionMapper;

    @Autowired(required = false)
    private ASysRolePermissionMapper aSysRolePermissionMapper;


    /**
     * 分页查询
     * @param formBean
     * @param pageNum
     * @param length
     * @return
     */
    @Override
    public ASysPermissionForm getByPage(ASysPermissionForm formBean, int pageNum, int length) {
        logger.info("分页查询--开始");
        //分页查询
        Example example = new Example(ASysPermission.class);
        Example.Criteria criteria = example.createCriteria();
        //权限名称
        if (StringUtils.isNotEmpty(formBean.getPermissionName())) {
            criteria.andLike("permissionName", "%" + formBean.getPermissionName() + "%");
        }
        //权限类型
        if (StringUtils.isNotEmpty(formBean.getType())) {
            criteria.andLike("type",  formBean.getType() );
        }
        //上级权限
        if (StringUtils.isNotEmpty(formBean.getParentGuid())) {
            criteria.andLike("parentGuid",  formBean.getParentGuid() );
        }
        example.orderBy("sort");

        PageHelper.startPage(pageNum, length);
        List<ASysPermission> permissionList = super.getByExample(example);

        formBean.setPageInfo(permissionList);
        logger.info("分页查询--结束");
        return  formBean;
    }

    /**
     *取得所有权限列表
     * @return
     */
    @Override
    public List<ASysPermission> getAll(){
        return aSysPermissionMapper.selectAllPermission();
    }



    /**
     *新增权限保存
     * @return
     */
    @Override
    public int save(ASysPermission aSysPermission){
        int retCnt=0;
        String strUrl=aSysPermission.getUrl().replace(FinalUtil.PERMISSION_MENU_BIAS,"");
        strUrl=FinalUtil.PERMISSION_MENU_BIAS + strUrl;
        String createUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        aSysPermission.setUpdateUserGuid(createUserGuid);
        aSysPermission.setCreatedUserGuid(createUserGuid);
        aSysPermission.setGuid(getGuid());
        if(FinalUtil.PERMISSION_TYPE_2.equals(aSysPermission.getType())){
            aSysPermission.setUrl( strUrl + FinalUtil.PERMISSION_MENU_URL);
        }
        retCnt = super.save(aSysPermission);
        //二级菜单：新增相关 查看，新增，修改，删除，上传，下载 权限设置
        if(FinalUtil.PERMISSION_TYPE_2.equals(aSysPermission.getType())){
            ASysPermission aSysPermissionSub = new ASysPermission();

            aSysPermissionSub.setUpdateUserGuid(createUserGuid);//更新人guid
            aSysPermissionSub.setCreatedUserGuid(createUserGuid);//创建人guid
            aSysPermissionSub.setParentGuid(aSysPermission.getGuid());//父级guid
            aSysPermissionSub.setType(FinalUtil.PERMISSION_TYPE_9);//权限类型

            for(String[]arrs:FinalUtil.PERMISSION_BUTTON){
                //权限设置
                aSysPermissionSub.setGuid(getGuid());//guid
                aSysPermissionSub.setPermissionName(aSysPermission.getPermissionName()+  arrs[0]);//权限名称
                aSysPermissionSub.setUrl(strUrl +  arrs[1]);//url
                aSysPermissionSub.setSort(aSysPermission.getSort() +arrs[2]);//顺序
                aSysPermissionSub.setRemark(aSysPermissionSub.getPermissionName());
                super.save(aSysPermissionSub);
            }
        }
        return retCnt;
    }

    /**
     *修改权限保存
     * @return
     */
    @Override
    public int update(ASysPermission aSysPermission){
        int retCnt=0;
        String createUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        aSysPermission.setUpdateUserGuid(createUserGuid);
        retCnt = super.update(aSysPermission);
        //二级菜单：新增相关 查看，新增，修改，删除，上传，下载 权限设置
        if(FinalUtil.PERMISSION_TYPE_2.equals(aSysPermission.getType())){
            //根据父级guid，查看，新增，修改，删除，上传，下载 权限取得
            Example example= new Example(ASysPermission.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("parentGuid", aSysPermission.getGuid());
            example.orderBy("sort");
            List<ASysPermission> aSysPermissionSubList = getByExample(example);

            for(ASysPermission aSysPermissionSub:aSysPermissionSubList){
                aSysPermissionSub.setUpdateUserGuid(createUserGuid);//更新人guid

                //三级权限名称更新
                String[] permissionNameArr = aSysPermissionSub.getPermissionName().split(FinalUtil.PERMISSION_MENU_MID);
                aSysPermissionSub.setPermissionName(aSysPermission.getPermissionName() + FinalUtil.PERMISSION_MENU_MID +permissionNameArr[1]);//权限名称

                //三级权限url更新
                String[] urlArr = aSysPermissionSub.getUrl().split(FinalUtil.PERMISSION_MENU_BIAS);
                aSysPermissionSub.setUrl(aSysPermission.getUrl() + FinalUtil.PERMISSION_MENU_BIAS  + urlArr[2]);//url

                //三级权限顺序更新
                String[] sortArr = aSysPermissionSub.getSort().split(FinalUtil.PERMISSION_MENU_MID);
                aSysPermissionSub.setSort(aSysPermission.getSort() + FinalUtil.PERMISSION_MENU_MID + sortArr[2]);//顺序

                aSysPermissionSub.setRemark(aSysPermissionSub.getPermissionName());

                super.update(aSysPermissionSub);

            }

        }
        return retCnt;
    }

    /**
     * 删除保存
     *
     * @return
     */
    @Override
    public  int delete(String permissionGuid){
        int retCnt=0;

        //删除权益guid对应的角色权限
        aSysRolePermissionMapper.deleteByPermission(permissionGuid);

        //删除权限
        retCnt=super.delete(permissionGuid);

        return retCnt;
    }

    /**
     * 根据用户GUID，取得用户所有权限列表
     * @param userGuid
     * @return
     */
    @Override
    public List<ASysPermission> getUserPermission(String userGuid) {

        return aSysPermissionMapper.selectUserPermission(userGuid);
    }

    /**
     * 取得权限下拉框初始列表
     * @return
     */
    @Override
    public List<ASysPermission> getSelectList() {
        logger.info("取得权限下拉框初始列表--开始");
        //查询条件：父亲权限下拉框初始化
        Example example= new Example(ASysPermission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("type", FinalUtil.PERMISSION_TYPE_9 );
        example.orderBy("sort");
        List<ASysPermission> permissionList = getByExample(example);

        List<ASysPermission> selectList = new ArrayList<ASysPermission>();
        ASysPermission baseMenu = new ASysPermission();
        baseMenu.setGuid("0");
        baseMenu.setPermissionName("根目录");
        selectList.add(baseMenu);
        for(ASysPermission aSysPermission:permissionList){
            //二级目录添加“--”字符
            if(FinalUtil.PERMISSION_TYPE_2.equals(aSysPermission.getType())){
                aSysPermission.setPermissionName(FinalUtil.PERMISSION_MENU_MID + aSysPermission.getPermissionName());
            }
            selectList.add(aSysPermission);
        }

        logger.info("取得权限下拉框初始列表--结束");
        return  selectList;
    }


    /**
     * 取得用户权限菜单取得
     * @param userGuid
     * @return
     */
    @Override
    public String getMenu(String userGuid) {

        List<ASysPermission> permissionList = aSysPermissionMapper.selectUserPermission(userGuid);

        List<Menu> menuList=new ArrayList<Menu>();//一级菜单列表
        List<MenuSub> menuSubList =new  ArrayList<MenuSub>();//二级菜单列表
        Menu menuBean= new Menu();
        MenuSub menuSubBean;

        for(ASysPermission permisson : permissionList){

            //取权限的类型,如果是1该类型为1级菜单，2为2级菜单
            switch (permisson.getType())
            {
                case "1":
                    //上一个一级菜单加入list
                    if(menuSubList.size()>0) {
                        menuBean.setSendMenuList(menuSubList);
                        menuList.add(menuBean);
                        menuSubList =new  ArrayList<MenuSub>();//二级菜单列表
                    }//这样的话最后一个菜单是加不进去的
                    //新的一级菜单
                    menuBean= new Menu();
                    menuBean.setOneMenuName(permisson.getPermissionName());
                    menuBean.setOneMenuUrl(permisson.getUrl());
                    menuBean.setOneMenuImg(permisson.getImg());
                    break;

                case "2":
                    menuSubBean=new MenuSub();
                    menuSubBean.setSecondMenuName(permisson.getPermissionName());
                    menuSubBean.setSecondMenuUrl(permisson.getUrl());
                    menuSubList.add(menuSubBean);
                    break;
                default:

                    break;
            }

        }

        //在最后需要再执行一次
        if(menuSubList.size()>0) {
            menuBean.setSendMenuList(menuSubList);
            menuList.add(menuBean);
        }

        return JSONArray.toJSONString(menuList);
    }
    /**
     * 查询所有出所有的角色权限（三张表关联：角色-角色权限-权限）
     * @return
     */
    public List<ASysPermissionForm> getAllRolesPermission(String _parameter){
        return aSysPermissionMapper.selectAllRolesPermission(_parameter);
    }
    /**
     * 根据角色guid，取得角色权限
     * @param roleGuidList
     * @return
     */
    public List<List<ASysPermission>> getRolePermission(List<String> roleGuidList){
        List<List<ASysPermission>> aSysPermissionList = new ArrayList<List<ASysPermission>>();
        for (String str:roleGuidList){
            List<ASysPermission> aSysPermission = new ArrayList<ASysPermission>();
            aSysPermission = aSysPermissionMapper.selectRolePermission(str);
            aSysPermissionList.add(aSysPermission);
        }
        return aSysPermissionList;
    }
}
